package com.example.lenovo.asia5b.my.myWallet.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.example.lenovo.asia5b.commodity.activity.ServiceActivity;
import com.example.lenovo.asia5b.my.activity.CreditCardUrlActivity;
import com.example.lenovo.asia5b.ui.LoadingDalog;
import com.example.lenovo.asia5b.util.DensityUtil;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.MD5;
import com.example.lenovo.asia5b.util.Setting;
import com.example.lenovo.asia5b.util.keyboardUtil;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import app.BaseFragment;
import fay.frame.ui.U;

import static com.example.lenovo.asia5b.util.Setting.getcreditstatus;
import static com.example.lenovo.asia5b.util.SharedPreferencesUtils.getUserBean;

/**
 * 信用卡
 * Created by lenovo on 2017/6/22.
 */

public class CreditCardFragment extends BaseFragment implements ICallBack {
    public View fragmentView;
    private TextView txt_expiration_time;
    private Switch sc_visa_card,sc_master_card;
    private EditText edit_card_number,edit_name,edit_security_cod;
    private EditText edit_other_amount;
    private TextView txt_500,txt_200,txt_100,txt_60;
    private Button btn_top_up;
    private List<TextView> RMTexts ;
    private LoadingDalog loadingDalog;
    private String strPasswor;
    private String cardType = "visacard";
    private int year,month;
    private String amount;
    private TextView txt_money;
    private LinearLayout ll_xy;
    private CheckBox chb_protocol;
    private String aid = "";


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        fragmentView = inflater.inflate(R.layout.frame_credit_card, container,
                false);

        initView();

        return fragmentView;
    }

    public void initView() {
        loadingDalog = new LoadingDalog(getActivity());
        sc_visa_card = (Switch)fragmentView.findViewById(R.id.sc_visa_card);
        sc_master_card= (Switch)fragmentView.findViewById(R.id.sc_master_card);
        edit_card_number = (EditText)fragmentView.findViewById(R.id.edit_card_number);
        edit_name = (EditText)fragmentView.findViewById(R.id.edit_name);
        txt_money = (TextView)fragmentView.findViewById(R.id.txt_money);
        edit_security_cod = (EditText)fragmentView.findViewById(R.id.edit_security_cod);
        edit_other_amount = (EditText)fragmentView.findViewById(R.id.edit_other_amount);
        txt_500 = (TextView)fragmentView.findViewById(R.id.txt_500);
        txt_200 = (TextView)fragmentView.findViewById(R.id.txt_200);
        txt_100 = (TextView)fragmentView.findViewById(R.id.txt_100);
        txt_60 = (TextView)fragmentView.findViewById(R.id.txt_60);
        btn_top_up = (Button)fragmentView.findViewById(R.id.btn_top_up);
        ll_xy= (LinearLayout)fragmentView.findViewById(R.id.ll_xy);
        ll_xy.setOnClickListener(this);
        chb_protocol = (CheckBox)fragmentView.findViewById(R.id.chb_protocol);

        RMTexts = new ArrayList<TextView>();
        RMTexts.add(txt_500);
        RMTexts.add(txt_200);
        RMTexts.add(txt_100);
        RMTexts.add(txt_60);
        for (int i = 0; i <RMTexts.size();i++) {
            RMTexts.get(i).setOnClickListener(new SelectOnClickListener(i));
        }
        btn_top_up.setOnClickListener(this);

        txt_expiration_time = (TextView)fragmentView.findViewById(R.id.txt_expiration_time);
        txt_expiration_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                keyboardUtil.HideKeyboard(edit_card_number);
                keyboardUtil.HideKeyboard(edit_name);
                keyboardUtil.HideKeyboard(edit_security_cod);
                keyboardUtil.HideKeyboard(edit_other_amount);
                TimePickerView pvTime = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date2, View v) {//选中事件回调
                        String time = getTime(date2);
                        String[] ss = time.split("-");
                        year = Integer.parseInt(ss[0]);
                        month = Integer.parseInt(ss[1]);
                        txt_expiration_time.setText(year+getResources().getString(R.string.n)+"-"+month + getResources().getString(R.string.y));
                    }
                })
                        .setType(TimePickerView.Type.YEAR_MONTH)//默认全部显示
                        .setCancelText(getResources().getString(R.string.qx))//取消按钮文字
                        .setSubmitText(getResources().getString(R.string.confirm))//确认按钮文字
                        .setContentSize(16)//滚轮文字大小
                        .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                        .isCyclic(true)//是否循环滚动
                        .setSubmitColor(ContextCompat.getColor(getActivity(),R.color.wathet))//确定按钮文字颜色
                        .setCancelColor(ContextCompat.getColor(getActivity(),R.color.wathet))//取消按钮文字颜色
                        .setLabel(getResources().getString(R.string.n),getResources().getString(R.string.y),getResources().getString(R.string.r),
                            getResources().getString(R.string.s),getResources().getString(R.string.f),"秒")
                        .isCenterLabel(false)
                        .build();
                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();
            }
        });
        sc_visa_card.setOnClickListener(this);
        sc_master_card.setOnClickListener(this);
        txt_money.setText("RM "+getUserBean().user_money);
        edit_other_amount.addTextChangedListener(new EditChangedListener(edit_other_amount));
        chb_protocol.setChecked(true);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_top_up:
                if (TextUtils.isEmpty(edit_card_number.getText().toString())) {
                    U.Toast(getActivity(),getResources().getString(R.string.xykbnwk));
                } else if (TextUtils.isEmpty(edit_name.getText().toString())) {
                    U.Toast(getActivity(),getResources().getString(R.string.my_data_hint_8));
                }  else if (year==0) {
                    U.Toast(getActivity(),getResources().getString(R.string.dqsjbnwk));
                } else if (TextUtils.isEmpty(edit_security_cod.getText().toString())) {
                    U.Toast(getActivity(),getResources().getString(R.string.aqmbnwk)
                    );
                }else if (TextUtils.isEmpty(edit_other_amount.getText().toString())&& TextUtils.isEmpty(amount)) {
                    U.Toast(getActivity(),getResources().getString(R.string.czjebnwk)
                    );
                }else if (!chb_protocol.isChecked()) {
                    U.Toast(getActivity(), getResources().getString(R.string.qgxyhxy));
                }else {
                    if (!TextUtils.isEmpty(edit_other_amount.getText().toString())) {
                        if (edit_other_amount.getText().toString().substring(0,1).equals(".")) {
                            return;
                        }
                    }
                    reditCardData();
                }
                break;
            case R.id.sc_visa_card:
                if (!sc_visa_card.isChecked()) {
                    sc_visa_card.setChecked(false);
                    sc_master_card.setChecked(true);
                    cardType = "mastercard";
                } else {
                    sc_visa_card.setChecked(true);
                    sc_master_card.setChecked(false);
                    cardType = "visacard";
                }
                break;
            case R.id.sc_master_card:
                if (!sc_master_card.isChecked()) {
                    sc_visa_card.setChecked(true);
                    sc_master_card.setChecked(false);
                    cardType = "visacard";
                } else {
                    sc_visa_card.setChecked(false);
                    sc_master_card.setChecked(true);
                    cardType = "mastercard";
                }
                break;
            case R.id.ll_xy:
                Intent intent = new Intent(getActivity(), ServiceActivity.class);
                intent.putExtra("xy","3");
                startActivity(intent);
                break;
            default:
                break;
        }
    }


    /**
     * 调用信用卡接口
     */
    public void reditCardData() {
        loadingDalog.show();
        //信用卡类型
        String cardType = this.cardType;
        //卡号
        String PAN = edit_card_number.getText().toString();
        //持卡人姓名
        String card_name = edit_name.getText().toString();
        //有效期年份
        String card_expiry_year =year+"";
        //有效期月份
        String card_expiry_month = "";
        if (month < 10){
            card_expiry_month = "0"+ month+"";
        } else {
            card_expiry_month =  month+"";
        }
        //安全码
        String CVV2 = edit_security_cod.getText().toString();
        //充值金额
        String amount ="";
        if (TextUtils.isEmpty(edit_other_amount.getText().toString())){
            amount = this.amount;
        } else {
            amount = edit_other_amount.getText().toString();
        }
        if (amount.indexOf(".")!=-1) {
            float aa = Float.parseFloat(amount);
            aa = DensityUtil.getScale(aa);
            amount = aa+"";
        }
        try {
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.CREDIT_PAY;
            String user_id = getUserBean().user_id;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id"+user_id,"time"+time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("user_id", user_id);
            parmaMap.put("cardType",cardType);
            parmaMap.put("PAN",PAN);
            parmaMap.put("card_name",card_name);
            parmaMap.put("card_expiry_month",card_expiry_month);
            parmaMap.put("card_expiry_year",card_expiry_year);
            parmaMap.put("CVV2",CVV2);
            parmaMap.put("amount",amount);
            parmaMap.put("time",time);
            parmaMap.put("sign",md5_32);
            JsonTools.getJsonAll(this, url, parmaMap, 0);
        } catch (Exception e) {

        }


    }

    public class SelectOnClickListener implements View.OnClickListener{
        int pos;
        public SelectOnClickListener(int pos) {
            this.pos = pos;
        }
        @Override
        public void onClick(View v) {
            for (int i = 0; i < RMTexts.size(); i++){
                RMTexts.get(i).setTextColor(ContextCompat.getColor(getActivity(), R.color.my_333));
                RMTexts.get(i).setBackgroundResource(R.drawable.shape_button_gray);
            }
            RMTexts.get(pos).setTextColor(ContextCompat.getColor(getActivity(), R.color.wathet3));
            RMTexts.get(pos).setBackgroundResource(R.drawable.shape_button_blue);
            edit_other_amount.setText("");
            String rm = RMTexts.get(pos).getText().toString();
            amount = rm.substring(2,rm.length());
        }
    }

    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result= null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;
            if (action == 0) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
//                        U.Toast(getActivity(), getResources().getString(R.string.cg));
                            JSONObject html = json.getJSONObject("html");
                            Intent intent = new Intent(getActivity(), CreditCardUrlActivity.class);
                            StringBuffer parmaMap = new StringBuffer();
                            parmaMap.append("merID="+html.getString("merID")+"&");
                            parmaMap.append("PAN="+html.getString("PAN")+"&");
                            parmaMap.append("expiryDate="+html.getString("expiryDate")+"&");
                            parmaMap.append("CVV2="+html.getString("CVV2")+"&");
                            parmaMap.append("invoiceNo="+html.getString("invoiceNo")+"&");
                            parmaMap.append("amount="+html.getString("amount")+"&");
                            parmaMap.append("secretCode="+html.getString("secretCode")+"&");
                            parmaMap.append("securityMethod="+"SHA1"+"&");
                            parmaMap.append("securityKeyReq="+html.getString("securityKeyReq")+"&");
                            parmaMap.append("postURL="+html.getString("postURL")+"&");
                            parmaMap.append("secretString="+""+"&");
                            parmaMap.append("bankName="+""+"&");
                            parmaMap.append("bankCountry="+"");
                            intent.putExtra("html",parmaMap.toString());
                            intent.putExtra("url",html.getString("url"));
                            String postURL = html.getString("postURL");
                            if (postURL.indexOf("aid")!= 1) {
                                String[] a = postURL.split("aid");
                                String b = a[1];
                                String[] c = b.split("&");
                                String d = c[0];
                                aid = d.substring(1,d.length());
                            }
                            startActivityForResult(intent,0);
                        } else if (state == 1) {
                            U.Toast(getActivity(), getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(getActivity(), getResources().getString(R.string.cscw));
                        } else if (state == 3) {
                            U.Toast(getActivity(), getResources().getString(R.string.wdl));
                        }
                    } catch (Exception e) {
                    }
                }
                loadingDalog.clearPassword();
                loadingDalog.dismiss();
            }   if (action == 1) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                            String pay_status = json.getString("pay_status");
                            if (pay_status.equals("0")) {
                                U.Toast(getActivity(), getResources().getString(R.string.czsb));
                            } else {
                                U.Toast(getActivity(), getResources().getString(R.string.cg));
                            }
                        } else if (state == 1) {
                            U.Toast(getActivity(), getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(getActivity(), getResources().getString(R.string.cscw));
                        } else if (state == 3) {
                            U.Toast(getActivity(), getResources().getString(R.string.wdl));
                        }
                    } catch (Exception e) {
                    }
                }
                loadingDalog.clearPassword();
                loadingDalog.dismiss();
            }
        }
    };

    @Override
    public void logicFinish(Object result, int action) {
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);
    }

    class EditRemarkdListener implements TextWatcher {

        public EditRemarkdListener() {

        }
        public EditRemarkdListener(EditText edit_count) {
        }
        private CharSequence temp;//监听前的文本
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (edit_other_amount.length() > 0) {
                for (int i = 0; i < RMTexts.size(); i++){
                    RMTexts.get(i).setTextColor(ContextCompat.getColor(getActivity(), R.color.my_333));
                    RMTexts.get(i).setBackgroundResource(R.drawable.shape_button_gray);
                }
                amount = "";
            }
        }
    };

    public void money(String user_money) {
        if (null != txt_money) {
            txt_money.setText("RM "+user_money);
        }
    }

    //=========================================获取充值状态==================================================
    public void getcreditstatus() {
        loadingDalog.show();
        try {
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = getcreditstatus;
            String user_id = getUserBean().user_id;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id"+user_id,"time"+time,"aid"+aid};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("user_id", user_id);
            parmaMap.put("aid", aid);
            parmaMap.put("time",time);
            parmaMap.put("sign",md5_32);
            JsonTools.getJsonAll(this, url, parmaMap, 1);
        } catch (Exception e) {

        }
    }


    // 回调方法，从第二个页面回来的时候会执行这个方法
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (resultCode) {
            case 0:
                if (data == null) {
                    return;
                }
                if (!data.hasExtra("creditCard")){
                    return;
                }
                if (null != loadingDalog) {
                    getcreditstatus();
                }
                break;
            default:
                break;
        }
    }

    public String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        return format.format(date);
    }

}
